//
//  DataCell.m
//  HeSaid
//
//  Created by MWJ on 15/5/4.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "DataCell.h"
#import "AppDelegate.h"
#import "ViewController.h"

#define resendpostURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/deletepost"//删除原来帖子
#define resend1postURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/repost"//重新发送
#define resend2postURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/repost1"//重新发送

@implementation DataCell{
    AppDelegate *delegate;
    NSString *resendStr;
    NSString *resendStr1;
    NSString *resendStr2;
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    UIAlertView *_alert;
    UIAlertView *_alert1;
    NSDictionary *roud;
}

- (void)awakeFromNib {
    [self.rebutton.layer setMasksToBounds:YES];
    [self.rebutton.layer setCornerRadius:5.0];
    delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }

    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
#pragma mark - 定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    NSString *locstr1 = @"http://restapi.amap.com/v3/assistant/coordinate/convert?locations=";
    NSString *locstr2 = [NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude];
    NSString *locstr3 = @"&coordsys=gps&output=json&key=b1ba3d04de3c8efdc866712f66033064";
    NSString *locstr4 = [NSString stringWithFormat:@"%@%@%@",locstr1,locstr2,locstr3];
    NSURL *url=[NSURL URLWithString:locstr4];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSString *poststr =@"";
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        roud = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:roud waitUntilDone:YES];
        NSArray *strarray = [roud[@"locations"] componentsSeparatedByString:@","];
        _longitude = [strarray[0] doubleValue];
        _latitude = [strarray[1] doubleValue];
    }];
}
-(void)refreshData{
    
}
- (IBAction)Resend:(id)sender {
    //开始定位
    [locationManager startUpdatingLocation];
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您确定要重新发表该帖子吗？"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    _alert = alert;
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        NSString *poststr =[NSString stringWithFormat:@"message_id=%@",self.messageID];
        [self londingPath:resendpostURL Str:poststr];
            }
    if (buttonIndex==0&&alertView==_alert1) {
        //跳转到主页
        [delegate haveView];
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ViewController *vc = [sb instantiateViewControllerWithIdentifier:@"viewVC"];
        [delegate.haveView pushViewController:vc animated:YES];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"ya" ofType:@"wav"];
        if (path) {
            //注册声音到系统
            AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:path]),&shake_sound_male_id);
            AudioServicesPlaySystemSound(shake_sound_male_id);
            //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
        }
        
        AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
        
        //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    }
}
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        resendStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:resendStr waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
        if ([resendStr isEqualToString:@"1"]) {
        NSDateFormatter *fomatter=[[NSDateFormatter alloc]init];
            [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *nowTime=[fomatter stringFromDate:[NSDate date]];
        NSString *poststr =[NSString stringWithFormat:@"user_id=%@&message_time=%@&message_longitude=%f&message_latitude=%f&message_content=%@&message_showtime=%@&message_Comment=%@",delegate.user_id,nowTime,_longitude,_latitude,self.messagecontent,self.messageshowtime,self.messagecomment];
            [self londingPath1:resend1postURL Str1:poststr];
        }
}
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        resendStr1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:resendStr1 waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender{
    if ([resendStr1 isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"帖子重新发送失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"帖子已经重新发送"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        _alert1 = alert;
        [alert show];
        NSString *poststr =[NSString stringWithFormat:@"id=%@&message_id=%@",self.messageID,resendStr1];
        [self londingPath2:resend2postURL Str2:poststr];
    }
}
-(void)londingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        resendStr2 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:resendStr2 waitUntilDone:YES];
    }];
}
-(void)refreshData2:(NSMutableArray *)sender{
}
@end
